package game.leon.engine.net;

import game.leon.engine.net.codec.GameRawMessage;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

/**
 * User: bianpeng
 * Date: 11-12-27
 */
class GameIoHandler extends IoHandlerAdapter {
    private Logger logger = Logger.getLogger(getClass());
    private static final String SESSION = "SESSION";
    private GameMessageHandler gameMessageHandler;
    public GameIoHandler(GameMessageHandler gameMessageHandler) {
        this.gameMessageHandler = gameMessageHandler;
    }
    @Override
    public void sessionOpened(IoSession session) {
        logger.debug("client connected: " + session.getRemoteAddress());
        GameRawMessage rawMessage = new GameRawMessage(
                EngineConsts.SESSION_OPEN, new byte[]{0, 0, 0, 1});
        GameSession saved = new GameSession(session);
        session.setAttribute(SESSION, saved);
        gameMessageHandler.execute(saved, rawMessage);
    }
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        GameRawMessage rawMessage = (GameRawMessage) message;
        logger.debug("message received from user: " + rawMessage.getMessage());
        GameSession saved = (GameSession) session.getAttribute(SESSION);
        assert saved != null && saved.getIoSession() == session;
        gameMessageHandler.execute(saved, rawMessage);
    }
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        logger.debug("client disconnected: " + session.getRemoteAddress());
        GameRawMessage rawMessage = new GameRawMessage(
                EngineConsts.SESSION_CLOSE, new byte[]{0, 0, 0, 1});
        GameSession saved = (GameSession) session.getAttribute(SESSION);
        assert saved != null && saved.getIoSession() == session;
        gameMessageHandler.execute(saved, rawMessage);
    }
}
